/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.ie.process;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Dictionary;

import org.iosgi.Constants;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.Version;
import org.osgi.util.tracker.ServiceTracker;

/**
 * @author Sven Schulz
 */
public class RemoteBundle implements InvocationHandler, Serializable {

	private static final long serialVersionUID = -2453313054869272625L;

	private final long bundleId;
	private transient BundleContext context;
	private transient Bundle b;

	RemoteBundle(long bundleId) {
		this.bundleId = bundleId;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if (context == null) {
			context = ProcessIE.getBundleContext();
		}
		if (b == null) {
			ServiceTracker t = new ServiceTracker(
					context,
					FrameworkUtil.createFilter("(&" + "(objectClass="
							+ Bundle.class.getName() + ")" + "("
							+ Constants.BUNDLE_ID + "=" + bundleId + ")" + ")"),
					null);
			t.open(true);
			// TODO Use system-wide timeout
			b = (Bundle) t.waitForService(0);
		}
		if (method.getName().equals("getVersion")) {
			Method m = Bundle.class.getMethod("getHeaders");
			Dictionary<String, Object> d = (Dictionary<String, Object>) m
					.invoke(b);
			return Version.parseVersion((String) d
					.get(org.osgi.framework.Constants.BUNDLE_VERSION));
		}
		return method.invoke(b, args);
	}

}
